package com.ai.exam.service.impl;

import com.ai.exam.dao.PrizeMapper;
import com.ai.exam.dao.UserHelpMapper;
import com.ai.exam.model.Prize;
import com.ai.exam.model.UserHelp;
import com.ai.exam.service.UserHelpService;
import com.ai.exam.core.AbstractService;
import com.ai.exam.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;


/**
 * Created by CodeGenerator on 2018/06/01.
 */
@Service
@Transactional
public class UserHelpServiceImpl extends AbstractService<UserHelp> implements UserHelpService {
    private Logger logger = LoggerFactory.getLogger(UserHelpServiceImpl.class);
    @Resource
    private UserHelpMapper userHelpMapper;
    @Resource
    private PrizeMapper prizeMapper;

    private String prizeId = "prize";

    @Override
    public Result addUserPrize(UserHelp userHelp) {
        logger.info("按openId查询被助力的用户，参数{}",userHelp);
        UserHelp rs = userHelpMapper.selectByPrimaryKey(userHelp.getOpenId());
        logger.info("查询结果{}",rs);
        if(rs!=null){
            logger.info("查看用户的助力人存不存在，结果{}",rs.getOpenIdHelp());
            if(rs.getOpenIdHelp()!=null){
                logger.info("已助力成功");
                return Result.fail("已助力成功");
            }else{
//                rs.setOpenIdHelp(userHelp.getOpenIdHelp());
//                rs.setTelnumHlep(userHelp.getTelnumHlep());
//                int i = userHelpMapper.updateByPrimaryKeySelective(rs);
//                logger.info("用户助力人修改结果{}",i);
//                return Result.success(i);

                rs.setOpenIdHelp(userHelp.getOpenIdHelp());
                rs.setTelnumHelp(userHelp.getTelnumHelp());
                rs.setHelpTime(new Date());
                Prize prize = prizeMapper.selectByPrimaryKey(prizeId);
                logger.info("查看奖品余量：{}",prize.getTotal());
                if(prize.getTotal()>0){
                    prize.setTotal(prize.getTotal()-1);
                    rs.setPrize(true);
                    int i = userHelpMapper.updateByPrimaryKeySelective(rs);
                    logger.info("用户助力人修改结果{}",i);
                    int j = prizeMapper.updateByPrimaryKeySelective(prize);
                    logger.info("修改奖品余量：{}",j);
                    return Result.success(i);
                }else{
                    int i = userHelpMapper.updateByPrimaryKeySelective(rs);
                    logger.info("奖品已发放完，只修改用户助力人 不领奖 {}",i);
                    return Result.success(null);
                }
            }
        }else{
            logger.info("不存在被指定的助力用户");
            return Result.fail("不存在被指定的助力用户");
        }
    }

    @Override
    public Result selUser(String openid) {
        UserHelp userHelp =userHelpMapper.selectByPrimaryKey(openid);
        logger.info("查询结果：{}",userHelp);
        return Result.success(userHelp);
    }
}
